package numberOfVisiblePeopleInAQueue_1944;

import java.util.Stack;

public class Solution {
    public int[] canSeePersonsCount(int[] heights) {
        Stack<Integer> stack = new Stack<>();
        int[] result = new int[heights.length];
        for (int i = heights.length - 1; i >= 0; i--) {
            if (stack.isEmpty()) {
                stack.add(i);
                continue;
            }
            int outCount = 0;
            while (!stack.isEmpty() && heights[stack.peek()] < heights[i]) {
                outCount++;
                stack.pop();
            }
            outCount += stack.isEmpty() ? 0 : 1;
            result[i] = outCount;
            stack.add(i);
        }
        return result;
    }
}
